
import axios from 'axios'

//axios.defaults.baseURL = 'https://127.0.0.1:8000/api';
let loginData
let user
export default {
    login({commit,dispatch},data){
        axios.post('http://127.0.0.1:8000/api/login',{
            username:data.email,
            password:data.password,
        })
        .then(res=>{
            console.log("data: ",res.data)
            loginData = res.data
            return axios.get('http://127.0.0.1:8000/api/user',{headers:{'Authorization':'Bearer '+res.data.access_token}})            
        })
        .then(res=>{
            commit('loggedIn',Object.assign(loginData,res.data))
            dispatch('getData',{})
            //return axios.get("http://127.0.0.1:8000/api/employees",{headers:{'Authorization':'Bearer '+loginData.access_token}})
        })
        .catch(err=>console.log(err))
    },
    logout({commit}){
        //todo: logout from the server
        commit('logout')
    },
    modifyEmployee({commit},emp){
        //todo: save emp to the server
        commit('replaceEmp',emp)
    },
    deleteEmp({commit},emp_id){
        //todo: delete from the database
        commit('deleteEmp',emp_id)
    },
    getData({commit,state},params){
        state.loading = true
        const user = JSON.parse(localStorage.getItem('user'))
        const access_token = user.access_token
        let query = "?"
        for (var k in params){
            if (params.hasOwnProperty(k)) {
                query += k+"="+params[k]+"&";
                //alert("Key is " + k + ", value is" + target[k]);
            }
        }
        axios.get("http://127.0.0.1:8000/api/employees"+query,{headers:{'Authorization':'Bearer '+access_token}})
        .then(res=>{
            console.log(res)
            commit('getData',res.data)
        })
        .catch(err=>{
            console.log(err)
        })
    }
}